from django.conf import settings
from celery import shared_task
from mysqldb.models import *
from mysqldb import redis as REDIS
from mysqldb import tasks as TASKS
from fsygManager.PulsarSDK import SendAsyncMessage
import time
import logging

logger = logging.getLogger(__name__)


@shared_task
def doMoniterPulsarScreen(topic, data):
    """
    发送大屏消息到队列
    topic: str 消息主题
    data: dict 消息数据
    """
    if str(topic).isdigit():
        item = settings.ALL_MODEL_PULSAR
        # message = json.dumps(data)
        cead = REDIS.clear_dict(data)
        message = str(cead)
        for i in item:
            SendAsyncMessage(f"{i}--{topic}", message)
        try:    
            r = TASKS.DoSendWebSocketMessages(topic, cead)
        except BaseException as err:
            r = f"{err}"
            logger.warn(f'[websocket] {err}')    
    return {"rescode": 200, "resmsg": r}


@shared_task
def doCallmeEvent(cid):
    """呼叫事件"""
    logger.info(f"[{cid}] 推送呼叫事件 新的消息")
    try:
        Callme = AllinpayCallmeList.objects.get(id=cid)
        pid = Callme.pid
        Conf = AllinpayCallmeConf.objects.get(id=Callme.rtype)
        workss = FsygPchardList.objects.get(name=Callme.source,pid=pid)
        group = workss.group
    except AllinpayCallmeList.DoesNotExist as err:
        logger.warning(f"[{cid}] 推送呼叫事件 查询呼叫订单异常")
        return {"rescode": 204, "resmsg": "推送呼叫事件 查询呼叫订单异常"}
    except AllinpayCallmeConf.DoesNotExist as err:
        logger.warning(f"[{cid}] 推送呼叫事件 查询呼叫订单选项异常")
        return {"rescode": 204, "resmsg": "推送呼叫事件 查询呼叫订单选项异常"}
    except FsygPchardList.DoesNotExist as err:
        group = "区域查询失败"
    except BaseException as err:
        logger.warning(f"[{cid}] [{err}] 推送呼叫事件 未知异常")
        return {"rescode": 204, "resmsg": "推送呼叫事件 未知异常"}
    # logger.info(f"[{cid}] 推送呼叫事件 验证完成")

    # 创建数据
    dbs = {
        "status": 5,
        "localhost": Callme.source,
        "group": group,
        "ipaddr": None,
        "mask": None,
        "gateway": None,
        "currenttime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "info": {"name": Conf.name, "message": "新的呼叫订单"},
    }
    # logger.info(f"[{cid}] 推送呼叫事件 创建数据结构完成")
    # 发送消息队列
    res = doMoniterPulsarScreen.apply_async((pid, dbs))
    # item = settings.ALL_MODEL_PULSAR
    # cead = REDIS.clear_dict(dbs)
    # message = str(cead)
    # for i in item:
    #     SendAsyncMessage(f"{i}--{pid}", message)
    # logger.info(f"[{cid}] 推送呼叫事件 发送消息队列完成")
    return {"rescode": 200, "resmsg": "ok"}


@shared_task
def doGoodEvent(gid):
    """打赏事件"""
    return {"rescode": 200, "resmsg": "暂未启用"}


@shared_task
def doGamesEvent(pid, data):
    """游戏事件"""
    host, name, status = data.get("host"), data.get("name"), data.get("status")
    res = REDIS.redis_hash_has("workStatus", f"{pid}--{host}", "games")
    gl = eval(res) if res else []
    if status == 1:
        gl.append(name)
    else:
        gl.remove(name)
    # 列表去重
    gl = list(set(gl))

    # 写入缓存
    REDIS.redis_hash_set(
        "workStatus", f"{pid}--{host}", {"localhost": host, "games": str(gl)}
    )
    # 创建数据
    dbs = {
        "status": 7,
        "localhost": host,
        "group": None,
        "ipaddr": None,
        "mask": None,
        "gateway": None,
        "currenttime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "games": gl,
    }
    res = doMoniterPulsarScreen.apply_async((pid, dbs))

    return {"rescode": 200, "resmsg": "暂未启用"}


@shared_task
def doPostEvent(pid):
    """员工岗位事件"""
    try:
        bind = AllinpayPlacestaffList.objects.get(id=pid)
        post = AllinpayPlacestaffPost.objects.get(id=pid)
        staff = AllinpayStaffList.objects.get(id=bind.sid)
        pid = bind.pid
    except AllinpayPlacestaffList.DoesNotExist as err:
        logger.warning(f"[{pid}] 推送岗位事件 查询在职员工异常")
        return {"rescode": 204, "resmsg": "推送岗位事件 查询在职员工异常"}
    except AllinpayPlacestaffPost.DoesNotExist as err:
        logger.warning(f"[{pid}] 推送岗位事件 查询在岗员工异常")
        return {"rescode": 204, "resmsg": "推送岗位事件 查询在岗员工异常"}
    except AllinpayStaffList.DoesNotExist as err:
        logger.warning(f"[{pid}] 推送岗位事件 查询员工属性异常")
        return {"rescode": 204, "resmsg": "推送岗位事件 查询员工属性异常"}
    except BaseException as err:
        logger.warning(f"推送岗位事件 未知异常")
        return {"rescode": 204, "resmsg": "推送岗位事件 未知异常"}
    # 创建数据
    dbs = {
        "status": 8,
        "localhost": None,
        "group": None,
        "ipaddr": None,
        "mask": None,
        "gateway": None,
        "currenttime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "post": {
            "id": bind.id,
            "basename": staff.basename,
            "nicename": staff.nicename,
            "status": post.status,
            "icon": staff.icon,
        },
    }
    res = doMoniterPulsarScreen.apply_async((pid, dbs))
    return {"rescode": 200, "resmsg": res}


@shared_task
def doWorkItemEvent(wid):
    """工作项完成事件"""
    try:
        item = AllinpayPlaceworkitemList.objects.get(id=wid)
        staff = AllinpayStaffList.objects.get(id=item.onstaff)
        pid = item.pid
    except AllinpayPlaceworkitemList.DoesNotExist as err:
        logger.warning(f"[{wid}] 推送工作项事件 查询工作项事务异常")
        return {"rescode": 204, "resmsg": "推送工作项事件 查询工作项事务异常"}
    except BaseException as err:
        logger.warning(f"推送工作项事件 未知异常")
        return {"rescode": 204, "resmsg": "推送工作项事件 未知异常"}
    # 创建数据
    dbs = {
        "status": 9,
        "localhost": None,
        "group": None,
        "ipaddr": None,
        "mask": None,
        "gateway": None,
        "currenttime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "item": {"id": item.id, "title": item.title, "outtype": item.outtype},
        "staff": {
            "id": staff.id,
            "basename": staff.basename,
            "nicename": staff.nicename,
        },
    }
    res = doMoniterPulsarScreen.apply_async((pid, dbs))
    return {"rescode": 200, "resmsg": res}
